package com.itheima.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.domain.YddArticle;
import com.itheima.youdianda.domain.YddUser;
import com.itheima.youdianda.domain.YddUserData;
import com.itheima.youdianda.dto.PageDto;
import com.itheima.youdianda.exception.CustomException;
import com.itheima.youdianda.service.YddArticleService;
import com.itheima.youdianda.service.YddUserService;
import com.itheima.youdianda.service.YddUserDataService;
import com.itheima.youdianda.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
@Transactional
public class UserController {
    @Autowired
     YddArticleService yddArticleService;
    @Autowired
    YddUserService yddUserService;
    @Autowired
     YddUserDataService yddUserDateService;

    /**
     * 问看文章分页
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/myArticle")
    public R<PageDto> page(int page, int limit,@RequestHeader("token") String token){
        log.info("获得的token为：{}", token);
        String getUserMobile = (String) JwtUtils.getUserValue(token,"mobile");
        //构造分页构造器对象
        Page<YddArticle> pageInfo = new Page<>(page,limit);
        // 条件构造器
        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.eq(YddUser::getMobile,getUserMobile);
        YddUser one = yddUserService.getOne(queryWrapper);
        String oneUsername = one.getUsername();
        LambdaQueryWrapper<YddArticle> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(YddArticle::getAuthor,oneUsername);
        yddArticleService.page(pageInfo,queryWrapper1);
        PageDto<YddArticle> pageDto = new PageDto<>();
        BeanUtils.copyProperties(pageInfo,pageDto);
        pageDto.setValue(pageInfo);
        return R.success(pageDto);
    }

    /**
     * 文章修改
     * @param yddArticle
     * @return
     */
    @PostMapping("/editArticle")
    public R update(@RequestBody YddArticle yddArticle){
        yddArticleService.updateById(yddArticle);
        return R.success("文章修改成功");
    }

    /**
     * 文章发布
     * @param yddArticle
     * @return
     */
    @PostMapping("/addArticle")
    public R add(@RequestBody YddArticle yddArticle){
        yddArticleService.save(yddArticle);
        return R.success("文章发布成功");
    }

    /**
     * 文章删除
     * @param id
     * @return
     */
    @GetMapping("/delArticle")
    public R del(Integer id){
        yddArticleService.removeById(id);
        return R.success("文章删除成功");
    }

    /**
     * 修改用户资料
     * @param user
     * @return
     */
    @PostMapping("/update")
    public R<String> update(@RequestBody YddUser user) {
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!ObjectUtils.isEmpty(user.getUsername()), YddUser::getUsername, user.getUsername());
        YddUser yddUser = yddUserService.getOne(wrapper);

        if (!ObjectUtils.isEmpty(yddUser) && !yddUser.getId().equals(user.getId())) {
            throw new CustomException("用户名已存在");
        }
        //对password进行MD5加密
        if (StringUtils.isNotEmpty(user.getPassword())) {
            String md5Pwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(md5Pwd);
        } else {
            user.setPassword(yddUser.getPassword());
        }
        yddUserService.updateById(user);
        return R.success("成功");
    }

//    /**
//     * 获取用户个人信息
//     * @param token
//     * @return
//     */
//    @GetMapping("/getUserInfo")
//    public Claims getInfo(@RequestHeader("token") String token){
//        Claims claims = JwtUtils.getClaims(token);
//        return null;
//    }

    /**
     * 获取点赞/收藏信息
     * @param page
     * @param limit
     * @param type
     * @param token
     * @return
     */
    @GetMapping("/userDataList")
    public R<PageDto> page(int page, int limit, int type,@RequestHeader("token") String token){
        String getUserMobile = (String) JwtUtils.getUserValue(token,"mobile");
        //构造分页构造器对象
        Page<YddArticle> pageInfo = new Page<>(page,limit);
        // 条件构造器
        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.eq(YddUser::getMobile,getUserMobile);
        YddUser one = yddUserService.getOne(queryWrapper);
        int UserId = one.getId();
        if (type == 1){
            LambdaQueryWrapper<YddUserData> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq( YddUserData:: getUserId , UserId);
            queryWrapper1.eq( YddUserData:: getType , 1);
            queryWrapper1.groupBy(YddUserData::getArticleId);
            List<YddUserData> list = yddUserDateService.list(queryWrapper1);
            LambdaQueryWrapper<YddArticle> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.in(YddArticle::getId,list);


            PageDto<YddArticle> pageDto = new PageDto<>();
            //查找
            yddArticleService.page(pageInfo, queryWrapper2);
            BeanUtils.copyProperties(pageInfo,pageDto);
            pageDto.setValue(pageInfo);
            return R.success(pageDto);
        }
        if (type == 2){
            LambdaQueryWrapper<YddUserData> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.eq( YddUserData:: getUserId , UserId);
            queryWrapper3.eq( YddUserData:: getType , 2);
            queryWrapper3.groupBy(YddUserData::getArticleId);
            List<YddUserData> list2 = yddUserDateService.list(queryWrapper3);
            LambdaQueryWrapper<YddArticle> queryWrapper4 = new LambdaQueryWrapper<>();
            queryWrapper4.in(YddArticle::getId,list2);

            PageDto<YddArticle> pageDto2 = new PageDto<>();
            //查找
            yddArticleService.page(pageInfo, queryWrapper4);
            BeanUtils.copyProperties(pageInfo,pageDto2);
            pageDto2.setValue(pageInfo);
            return R.success(pageDto2);
        }
        return R.error("失败");
    }

    /**
     * 修改点赞/收藏信息
     * @param type
     * @param action
     * @param articleId
     * @param token
     * @return
     */
    @GetMapping("/userDataHandle")
    public R<String> userDataHandle(Integer type,String action,Integer articleId,@RequestHeader("token") String token){
        LambdaQueryWrapper<YddUserData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUserData::getArticleId,articleId);
        queryWrapper.eq(YddUserData::getType,type);
        YddUserData yddUserData=yddUserDateService.getOne(queryWrapper);
        log.info("获得的token为：{}", token);
        Claims claims =JwtUtils.getClaims(token);
        Object ido = claims.get("id");
        String id = String.valueOf(ido);
        int userId = Integer.parseInt(id);
        if (null!=yddUserData&&"del".equals(action)) {
            yddUserDateService.remove(queryWrapper);
        }
        if("add".equals(action)){
            YddUserData yddUserData1 = new YddUserData();
            yddUserData1.setUserId(userId);
            yddUserData1.setArticleId(articleId);
            yddUserData1.setType(type);
            yddUserDateService.save(yddUserData1);
        }
        return R.success("操作成功");
    }


    @GetMapping("/getUserInfo")
    public R<Map> getUserInfo(@RequestHeader("token") String token){
        log.info("获得的token为：{}", token);
        String getUserMobile = (String)JwtUtils.getUserValue(token,"mobile");
        LambdaQueryWrapper<YddUser> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(YddUser::getMobile,getUserMobile);
        YddUser one = yddUserService.getOne(lambdaQueryWrapper);
        Map map = new HashMap();
        map.put("userInfo",one);
        return R.success(map);
    }

}
